package org.example.mywebsite.controller;

import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Update;
import org.example.mywebsite.entity.Essay;
import org.example.mywebsite.mapper.EssayMapper;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Timer;

@RestController
@RequestMapping("/admin")
@Slf4j
@RequiredArgsConstructor
public class AdminController {

    private final EssayMapper essayMapper;

    @GetMapping
    @Operation(summary = "验证管理员身份")
    public boolean admin() {
        log.info("验证身份");
        return true;
    }

    @PostMapping("/write")
    public void write(@RequestBody Essay essay) {
        log.info("写文章");
        try {
            String time = LocalDateTime.now().toString();
            essay.setTime(time);
            essayMapper.insert(essay);
        } catch (Exception e) {
            log.error("写文章失败:{}", e);
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/articles")
    public List<Essay> list(){
        log.info("管理员获取文章列表");
        return essayMapper.selectList(null);
    }

    @PostMapping("/articles")
    public void update(@RequestBody Essay essay) {
        log.info("管理员更新文章");
        try {
            essayMapper.updateById(essay);
        } catch (Exception e) {
            log.error("更新文章失败:{}", e);
            throw new RuntimeException(e);
        }
    }

    @DeleteMapping("/articles")
    public void delete(@RequestParam Integer id){
        log.info("管理员删除文章:id={}", id);
        try{
            essayMapper.deleteById(id);
        } catch (Exception e) {
            log.error("删除文章失败:{}", e);
            throw new RuntimeException(e);
        }
    }
}
